package com.zeldu.common.exception;

import com.google.common.collect.ImmutableMap;
;
import com.zeldu.common.model.response.CommonCode;
import com.zeldu.common.model.response.ResponseResult;
import com.zeldu.common.model.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * @Author: 李鸽
 * @Description: 通用的返回状态码
 * @Date:Created in 2019/1/24 18:33.
 * @Modified By:
 */

/**
 * 同一异常捕获类
 */
@ControllerAdvice
public class ExceptionCatch {
    //使用EXCEPTIONS存放异常类型和错误代码的映射，ImmutableMap的特点的一旦创建不可改变，并且线程安全
    private static ImmutableMap<Class<? extends  Throwable>,ResultCode> EXCEPITONS;
    protected static ImmutableMap.Builder<Class<? extends Throwable>,ResultCode> builder=ImmutableMap.builder();

    private static final Logger LOGGER= LoggerFactory.getLogger(ExceptionCatch.class);

/*
* 手动抛出的异常
* */

@ExceptionHandler(CustomException.class)
@ResponseBody
    public ResponseResult customeException(CustomException c){
    LOGGER.error("catch exception:{}",c.getMessage());
    ResultCode resultCode = c.getResultCode();
    return new ResponseResult(resultCode);
}
/*
* 对系统抛出的不可知异常做统一处理
* */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult catchException(Exception c){
      LOGGER.error("catch exception:{}",c.getMessage());

//org.springframework.security.access.AccessDeniedException: 不允许访问
        if(EXCEPITONS==null){
            EXCEPITONS=builder.build();
        }
        ResultCode resultCode = EXCEPITONS.get(c.getClass());
        if (resultCode!=null){
            return new ResponseResult(resultCode);
        }else {

            return new ResponseResult(CommonCode.SERVER_ERROR);
       }
    }
static {
    builder.put(HttpMessageNotReadableException.class,CommonCode.INVALID_PARAM);
    //builder.put(AccessDeniedException.class,CommonCode.UNAUTHORISE);
}
//static {
//    builder.put(HttpMessageNotReadableException.class,CommonCode.INVALID_PARAM);
//}



}
